package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.pojo.resp.BaseResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RequestMapping("/pay")
@Api(tags = "支付管理")
@Controller
/**
 * 支付宝支付
 */
public class PayController {

    private static final String privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCeVAgdg6dzz3RbiZr2cq/7bplhDtZwT8ctO+V68WgwloktwEgCmoeqwOQMpboppRZoZt7cn/QFg3FKNxMOVypLx5EawSarothdo6NH2Qe5IIj6fiK1Zw8PtBEdFbhEgIk8dmdq+8tYHD+FnrWI6VDfz65C0WYORGOgiUkZPBlajUCVlrY/2AfU/3x+Re+6TsUy8K5qyY8bCyvueLORFCnxrxFbgTrV7i6BACV97bInNUzOQbOhL1NuybYAXCQCENvc3R9v1V15KYJ8ftHvL1vQv3mvp5pxMhmNYK7vBuvZTXgF9E9CiTxoq76bddvmF9RO6PTmnWr0PZPTwY0XxC7vAgMBAAECggEAId9ugQn6mE9I4JCXA6TTu6IU1Gv9OrgGr8nBtcTR+psqLAyYG15+KezsnTwTkPdNzPY9NcxOw6M0aKFRxV6moOHITIYIRO4pBheNRkDLYzLvu0+jE1ZCJaTriGJuMtGhCrt2MrA999LLUEX9JpZsBAYFjSwJfoHpIp5ccjamYfXAg8iuBjF/tgu+Ep44qmTMWixNe9Ti5XyIJRVQLrqTZ7sL+ktAC/aPOMlIGGSpt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ItPirq14Tvoe+deP/W2myMUET99zT9k0fqfMluUMb8cr3agu5Um1VmpdNpevp0XIKIPDH47rABTL8X8XmI2FN7siroPY95eBmy4w/sRg6dee/5wk9/mR7qz4vqLEAFuQXhqQot7rYf6k2OtRImZs4S/1CNJwoCkGAYhms6lqXwlS5nztXlvetqk4IDt7Ps0S2pTfq1iQf8MKkiKLzMcd2X4eRNGTvQfgiBtZU0DXxhTsCj+kcWiEPJmmx6VueM96TKz1Q402o8o6Z5PHisCvvLpvCl/7adi1sFGsI+crC5Zkcz5Z0bJ8rAthrCDfwIDAQAB";
    @GetMapping("/alipay")
    @ApiOperation("支付宝支付接口(money必传)")
    public void pay(double money,HttpServletRequest httpRequest,
                    HttpServletResponse httpResponse) throws IOException {
        //1.生成支付宝请求客户端 1.serverURL 代表 请求的支付宝网关地址 2.appid 商户的标识 3.应用私钥。4.格式转换 默认时Json .5. 编码格式 默认是 utf-8 6.支付宝公钥。7.加密方式默认是 RSA2
        AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipaydev.com/gateway.do" , "2021000121674699", privateKey, "json", "utf-8", alipaypubicKey, "RSA2");  //获得初始化的AlipayClient
        //2.声明交易方式，网页端支付
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //3.returnurl 支付宝同步返回的参数页面
        alipayRequest.setReturnUrl( "http://123.56.105.30:8088/pay/success" );
//        alipayRequest.setReturnUrl( "http://localhost:8088/pay/success" );
//        alipayRequest.setReturnUrl( "" );
        //4.NotifyUrl 支付宝的异步通知
        alipayRequest.setNotifyUrl( "http://123.56.105.30:8088/pay/notifyUrl" ); //在公共参数中设置回跳和通知地址
        //5.设置支付的参数 out_trade_no 订单号必须保持唯一 product_code 固定为 FAST_INSTANT_TRADE_PAY total_amount 价格，subject 主题 body 内容
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", UUID.randomUUID().toString());
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        jsonObject.put("total_amount", String.valueOf(money));
        jsonObject.put("subject", "商品总额");
//        jsonObject.put("body", "包子是金子馅");
        //入库，设置支付状态为未支付状态
        alipayRequest.setBizContent(jsonObject.toJSONString()); //填充业务参数
        String form= "" ;
        try  {
            //请求支付宝 获取到支付表单 form表单
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType( "text/html;charset=utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notifyUrl")
    public void notfiyUrl(HttpServletRequest request) throws AlipayApiException {
        //将异步通知中收到的所有参数都存放到map中 将Request请求中的参数重组为map集合
        Map<String, String> paramsMap = convertRequestParamsToMap(request);

        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipaypubicKey, "utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println("验签成功！！！");
            System.out.println("当前回调的订单编号为:"+paramsMap.get("out_trade_no"));
            System.out.println("当前回调的appid为:"+paramsMap.get("app_id"));
            System.out.println("当前订单支付的金额为:"+paramsMap.get("total_amount"));
            System.out.println("当前订单状态为:"+paramsMap.get("trade_status"));
            //通过订单号更改数据库的该笔订单的交易状态

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

//    支付成功跳转页面
    @GetMapping("success")
    public String success(){
        return "/success.html";
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

}
